package org.example.demo1.controller;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.example.demo1.config.MonitorConfig;
import org.example.demo1.service.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 监控系统控制器
 * 提供Grafana、Prometheus和Kubernetes的监控数据接口
 */
@Slf4j
@RestController
@RequestMapping("/api/monitor")
@RequiredArgsConstructor
public class MonitorController {
    private final MonitorService monitorService;
    @Autowired
       private MonitorConfig monitorConfig;

    /**
     * 获取Grafana仪表板列表
     * @return 仪表板列表
     */
    @GetMapping("/grafana/search")
    public ResponseEntity<List<Map<String, Object>>> getGrafanaSearch() {
        return ResponseEntity.ok(monitorService.getGrafanaDashboards());
    }

    /**
     * 获取指定仪表板的详细信息
     * 通过仪表板UID获取特定仪表板的完整配置和数据
     * 
     * @param uid 仪表板的唯一标识符
     * @return 仪表板的详细信息
     */
    @GetMapping("/grafana/dashboards/{uid}")
    public Map<String, Object> getGrafanaDashboard(@PathVariable String uid) {
        return monitorService.getGrafanaDashboard(uid);
    }

    /**
     * 查询Prometheus指标数据
     * 支持PromQL查询语言，可以获取各种监控指标
     * 
     * @param query PromQL查询语句
     * @return 查询结果
     */
    @GetMapping("/prometheus/metrics")
    public Map<String, Object> getPrometheusMetrics(@RequestParam String query) {
        return monitorService.getPrometheusMetrics(query);
    }

    /**
     * 获取Kubernetes Pod列表
     * 返回指定命名空间下的所有Pod信息
     * 
     * @return Pod列表
     */
    @GetMapping("/k8s/pods")
    public List<Pod> getK8sPods() {
        return monitorService.getK8sPods();
    }

    /**
     * 获取Kubernetes事件列表
     * 返回指定命名空间下的所有事件信息
     * 
     * @return 事件列表
     */
    @GetMapping("/k8s/events")
    public List<Event> getK8sEvents() {
        return monitorService.getK8sEvents();
    }

    /**
     * 获取指定Pod的日志
     * 返回特定Pod的实时日志内容
     * 
     * @param podName Pod名称
     * @return Pod的日志内容
     */
    @GetMapping("/k8s/pods/{podName}/logs")
    public String getK8sPodLogs(@PathVariable String podName) {
        try {
            log.info("正在获取Pod {} 的日志", podName);
            
            Config config = new ConfigBuilder()
                    .withMasterUrl(monitorConfig.getKubernetes().getMasterUrl())
                    .withOauthToken(monitorConfig.getKubernetes().getToken())
                    .withTrustCerts(true)
                    .build();

            try (KubernetesClient client = new KubernetesClientBuilder()
                    .withConfig(config)
                    .build()) {
                
                // 指定容器名称为 "server"
                String logs = client.pods()
                        .inNamespace(monitorConfig.getKubernetes().getNamespace())
                        .withName(podName)
                        .inContainer("server")  // 指定容器名称
                        .getLog(true);
                
                if (logs == null || logs.isEmpty()) {
                    log.warn("Pod {} 没有日志", podName);
                    return "没有日志";
                }
                
                log.info("成功获取Pod {} 的日志", podName);
                return logs;
            }
        } catch (Exception e) {
            log.error("获取Pod {} 的日志失败: {}", podName, e.getMessage(), e);
            throw new RuntimeException("获取Pod日志失败: " + e.getMessage());
        }
    }

    @GetMapping("/prometheus/labels/{label}/values")
    public ResponseEntity<Map<String, Object>> getPrometheusLabelValues(@PathVariable String label) {
        try {
            String query = String.format("label_values(%s)", label);
            return ResponseEntity.ok(monitorService.getPrometheusMetrics(query));
        } catch (Exception e) {
            log.error("获取Prometheus标签值失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取集群故障状态
     * 返回当前集群的整体状态和详细指标信息
     * 
     * @return 故障状态信息
     */
    @GetMapping("/fault/status")
    public Map<String, Object> getFaultStatus() {
        return monitorService.getFaultStatus();
    }

    /**
     * 获取 Grafana 的基础 URL
     * @return Grafana 的 URL
     */
    @GetMapping("/grafana/url")
    public ResponseEntity<Map<String, String>> getGrafanaUrl() {
        String url = monitorConfig.getGrafana().getUrl();
        if (url != null && !url.isEmpty()) {
            return ResponseEntity.ok(Collections.singletonMap("url", url));
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Collections.singletonMap("error", "Grafana URL not configured"));
        }
    }
    @GetMapping("/k8s/pods/detail")
    public List<Map<String, Object>> getK8sPodsDetail() {
        return monitorService.getK8sPodsDetail();
    }

    @GetMapping("/k8s/nodes/detail")
    public List<Map<String, Object>> getK8sNodesDetail() {
        return monitorService.getK8sNodesDetail();
    }
} 